<template>
  <!-- 调试 -->
  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <!--  订阅消息tab页显示  -->
      <el-tab-pane v-if="subscribeMessagesVisible" label="订阅消息" name="first">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">

          <el-form-item
            v-if="subscribeResponseDataVisible"
            label="响应数据"
            prop="subscribeResponseData"
            label-position="left"
            label-width="120px"
          >
            <el-input
              type="textarea"
              placeholder="16进制请使用Ox开头"
              :autosize="{ minRows: 9, maxRows: 9}" v-model="form.subscribeResponseData"
              class="responseData"
            />
          </el-form-item>

          <el-form-item v-if="subscribeTopicVisible" label="推送Topic" prop="subscribeTopic">
            <el-input v-model="form.subscribeTopic" placeholder="请输入"/>
          </el-form-item>

          <!-- 数据类型-->
          <el-form-item
            v-if="subscribeDataTypeVisible"
            label="数据类型"
            prop="subscribeDataType"
          >
            <el-select
              v-model="form.subscribeDataType"
              @change="changeDataType"
              placeholder="请选择数据类型"
              class="select-width"
            >
              <el-option
                v-for="dict in dict.type.iot_network_data_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

        </el-form>
      </el-tab-pane>

      <!-- 不存在tab页时-->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <!-- 数据类型-->
        <el-form-item
          v-if="dataTypeVisible"
          label="数据类型"
          prop="dataType"
        >
          <el-select v-model="form.dataType" @change="changeDataType" placeholder="请选择数据类型" class="select-width">
            <el-option
              v-for="dict in dict.type.iot_network_data_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item
          v-if="responseDataVisible"
          label="响应数据"
          prop="response"
          label-position="left"
          label-width="120px"
        >
          <el-input
            type="textarea"
            placeholder="16进制请使用Ox开头"
            :autosize="{ minRows: 9, maxRows: 9}"
            v-model="form.response"
            class="responseData"
          />
        </el-form-item>

      </el-form>
      <!--  推送消息tab页显示  -->
      <el-tab-pane v-if="pushMessageVisible" label="推送消息" name="second">

        <el-form ref="pushForm" :model="pushForm" :rules="rules" label-width="80px">
          <el-form-item v-if="topicVisible" label="推送Topic" prop="topic">
            <el-input v-model="pushForm.parameter.topic" placeholder="请输入"/>
          </el-form-item>

          <!-- 数据类型-->
          <el-form-item
            v-if="pushDataTypeVisible"
            label="数据类型"
            prop="pushDataType"
          >
            <el-select
              v-model="pushForm.pushDataType"
              @change="changeDataType"
              placeholder="请选择数据类型"
              class="select-width"
            >
              <el-option
                v-for="dict in dict.type.iot_network_data_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>


          <el-form-item v-if="pushDataVisible" label="推送数据" prop="data">
            <el-input type="textarea" v-model="pushForm.parameter.data" placeholder="请输入"/>
          </el-form-item>

          <el-form-item
            v-if="pushRequestDataVisible"
            label="请求数据"
            prop="request"
            label-position="left"
            label-width="120px"
          >
            <el-input
              type="textarea"
              placeholder="16进制请使用Ox开头"
              :autosize="{ minRows: 9, maxRows: 9}"
              v-model="pushForm.parameter.request"
              class="responseData"
            />
          </el-form-item>

        </el-form>

      </el-tab-pane>
    </el-tabs>

    <el-divider><span>调试日志</span></el-divider>

    <div class="debug-result">
      <el-row v-for="(item, index) in debugData" :key="index">
        <el-col>
          <span>{{ item.title }}</span>
          <div v-for="(datum, index) in item.data" :key="index">{{ datum }}</div>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="startDebug">开 始</el-button>
      <el-button type="danger" @click="endDebug">结 束</el-button>
      <el-button plain @click="emptyDebug">清 空</el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>


export default {
  name: 'NetworkDebug',
  dicts: ['iot_network_data_type'],
  components: {},
  data() {
    return {
      // 弹出层标题
      title: '',
      // 组件类型
      type: undefined,
      // 是否显示弹出层
      open: false,
      //单个组件数据
      networkData: [],
      parameter:{},
      // 表单参数
      form: {
        subscribeResponseData: null,
        subscribeTopic: null,
        subscribeDataType: 'JSON',
        response: null,
        dataType: 'JSON'
      },
      pushForm: {
        pushDataType: 'JSON',
        parameter: {}
      },
      debugData: [],
      debugType: '',
      debugEnd: '',
      debugId: '',
      tabPaneName: 'first',
      topics: '',
      dataTypes: 'JSON',
      activeName: 'first',
      //输入框 推送Topic 默认 不显示
      topicVisible: false,
      //输入框 推送数据 默认 不显示
      pushDataVisible: false,
      //输入框请求数据 默认 不显示
      pushRequestDataVisible: false,
      //输入框响应数据 默认 不显示
      responseDataVisible: false,
      // 推送消息 默认 不显示
      pushMessageVisible: false,
      //数据类型 默认 不显示
      dataTypeVisible: false,
      //订阅消息 默认不显示
      subscribeMessagesVisible: false,
      //订阅消息---订阅Topic
      subscribeTopicVisible: false,
      //订阅消息--数据类型
      subscribeDataTypeVisible: false,
      //订阅消息--相应数据
      subscribeResponseDataVisible: false,
      //推送-数据类型
      pushDataTypeVisible: false,
      // 表单校验
      rules: {}
    }
  },
  watch: {
    type(type) {
      this.visibleByNetWorkType(type)
      this.analysisType(type)
    }
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        dataType: 'JSON',
        subscribeDataType: 'JSON'
      }
      this.resetForm('form')
    },

    /** 取消按钮操作 */
    cancel() {
      this.open = false
      this.reset()
      this.debugData = []
    },

    /** 切换标签页触发事件 */
    handleClick(tab) {
      this.tabPaneName = tab.name
      this.analysisType(this.type)
    },

    /** 调试按钮操作 */
    handleDebugging(row) {
      this.reset()
      this.pushForm = {
        parameter: {},
        pushDataType: 'JSON'
      }
      this.open = true
      this.title = row.typeName
      this.type = row.type
      this.networkData = row
      this.debugId = '';
      //调试按钮执行时，执行一次结束调试和清除调试记录
      // this.endDebug()
      this.emptyDebug()
    },
    /** 解析数据类型 */
    analysisType(type) {
      let types = []
      types = type.split('_')
      //取数组中的数据，并转小写
      this.debugType = types[0].toLowerCase()
      this.debugEnd = types[1].toLowerCase()

      this.processingTopics()
    },

    /** 根绝类型处理topics */
    processingTopics() {

      if (this.debugType === 'tcp') {

        if (this.debugEnd === 'client' && this.tabPaneName === 'second') {
          this.topics = `/network/${this.debugType}/${this.debugEnd}/${this.networkData.id}/_send`
        } else {
          this.topics = `/network/${this.debugType}/${this.debugEnd}/${this.networkData.id}/_subscribe`
        }

      }
      if (this.debugType === 'mqtt') {

        if (this.debugEnd === 'client' && this.tabPaneName === 'second') {
          this.topics = `/network/${this.debugType}/${this.debugEnd}/${this.networkData.id}/_publish/${this.dataTypes}`
        } else {
          this.topics = `/network/${this.debugType}/${this.debugEnd}/${this.networkData.id}/_subscribe/${this.dataTypes}`
        }

      }
    },

    /** 选择数据类型触发事件 */
    changeDataType() {
      //此时订阅消息和推送消息同时存在  类型为mqtt客户端
      if (this.subscribeMessagesVisible === true && this.pushMessageVisible === true) {
        this.dataTypes = this.form.subscribeDataType === undefined ? 'JSON' : this.form.subscribeDataType
        //此时为mqtt服务端 只有一个数据类型
      } else if (this.dataTypeVisible) {
        this.dataTypes = this.form.dataType
      } else {
        this.dataTypes = 'JSON'
      }

      this.processingTopics()
    },

    /** 处理表单数据到 parameter 中 */
    getParameter(){
      this.parameter = {};
      if (this.debugType === 'tcp') {
        if (this.debugEnd === 'server'){
          this.parameter['response'] = this.form.response;
        }else {
          if (this.tabPaneName === 'first'){
            this.parameter['response'] = this.form.subscribeResponseData;
          }else {
            this.parameter['request'] = this.pushForm.parameter.request;
          }

        }
      }
      if (this.debugType === 'mqtt') {
        if (this.debugEnd === 'server'){
          this.parameter = {};
        }else {
          if (this.tabPaneName === 'first'){
            this.parameter['topics'] = this.form.subscribeTopic;
          }else {
            this.parameter['topic'] = this.pushForm.parameter.topic;
            this.parameter['data'] = this.pushForm.parameter.data;
            // this.parameter['retain'] = true;
          }
        }
      }
    },

    /** 开始调试 */
    startDebug() {
      // 对 debugId 进行拼接处理
      this.processingNetWorkType()
      this.getParameter();

      this.debugData.push({
        title: '开始调试',
        data: []
      })

      // 发送订阅消息
      this.socket.send({
        method: 'event',
        params: {
          subEvent: 'sub',
          content: {
            type: 'sub',
            id: this.debugId,
            parameter:  this.parameter,
            topic: this.topics
          }
        }
      }).then(data => {
        const payload = data.payload
        const lastData = this.debugData[this.debugData.length - 1]
        if (lastData) {
          lastData.data.push(payload)
        }
      })
    },

    /** 结束调试 */
    endDebug() {
      this.debugData.push({
        title: '结束调试'
      })
      // 发送订阅消息
      this.socket.send({
        method: 'event',
        params: {
          subEvent: 'unsub',
          content: {
            type: 'unsub',
            id: this.debugId
          }
        }
      })
    },
    /** 清空调试 */
    emptyDebug() {
      this.debugData = [{
        data: []
      }]
    },

    /** 对调试中 id 进行处理 */
    processingNetWorkType() {
      if (this.debugEnd === 'client' && this.tabPaneName === 'first') {
        this.debugId = this.debugType + '-' + this.debugEnd + '-debug-subscribe'
      } else if (this.debugEnd === 'client' && this.tabPaneName === 'second') {

        if (this.debugType === 'tcp') {
          this.debugId = this.debugType + '-' + this.debugEnd + '-debug-send'
        } else {
          this.debugId = this.debugType + '-' + this.debugEnd + '-debug-publish'
        }

      } else {
        this.debugId = this.debugType + '-' + this.debugEnd + '-debug'
      }
    },

    /**
     * 根据网络组件类型显示隐藏表单
     * @param type 网络组件类型
     */
    visibleByNetWorkType(type) {
      if (!type) {
        //响应数据 不显示
        this.responseDataVisible = false
        //数据类型 不显示
        this.dataTypeVisible = false
        //订阅消息--订阅Topic 不显示
        this.subscribeTopicVisible = false
        //订阅消息--数据类型 不显示
        this.subscribeDataTypeVisible = false
        //推送--Topic
        this.topicVisible = false
        //推送--数据
        this.pushDataVisible = false

        //推送--请求数据 不显示
        this.pushRequestDataVisible = false
        //推送消息 不显示
        this.pushMessageVisible = false
        //订阅消息 不显示
        this.subscribeMessagesVisible = false
        //订阅--响应数据
        this.subscribeResponseDataVisible = false

        //推送--数据类型
        this.pushDataTypeVisible = false

      } else if (type === 'TCP_CLIENT') {
        //推送--请求数据
        this.pushRequestDataVisible = true
        //推送消息
        this.pushMessageVisible = true
        //订阅-- 响应数据
        this.subscribeResponseDataVisible = true
        //订阅消息
        this.subscribeMessagesVisible = true

        //相应数据 不显示
        this.responseDataVisible = false
        //数据类型 不显示
        this.dataTypeVisible = false
        //订阅消息--订阅Topic
        this.subscribeTopicVisible = false
        //订阅消息--数据类型
        this.subscribeDataTypeVisible = false
        //Topic
        this.topicVisible = false
        //推送数据
        this.pushDataVisible = false
        //推送--数据类型
        this.pushDataTypeVisible = false

      } else if (type === 'TCP_SERVER') {
        //响应数据
        this.responseDataVisible = true
        //请求数据 不显示
        this.pushRequestDataVisible = false
        //订阅消息---相应数据 不显示
        this.subscribeResponseDataVisible = false
        //推送消息 不显示
        this.pushMessageVisible = false
        //数据类型 不显示
        this.dataTypeVisible = false
        //订阅消息 不显示
        this.subscribeMessagesVisible = false
        //订阅消息--订阅Topic
        this.subscribeTopicVisible = false
        //订阅消息--数据类型
        this.subscribeDataTypeVisible = false
        // Topic
        this.topicVisible = false
        //推送数据
        this.pushDataVisible = false
        //推送--数据类型
        this.pushDataTypeVisible = false
      } else if (type === 'MQTT_SERVER') {
        //数据类型
        this.dataTypeVisible = true
        //订阅消息--订阅Topic
        this.subscribeTopicVisible = false
        //订阅消息--数据类型
        this.subscribeDataTypeVisible = false
        this.topicVisible = false
        //推送数据
        this.pushDataVisible = false
        //请求数据 不显示
        this.pushRequestDataVisible = false
        //推送消息 不显示
        this.pushMessageVisible = false
        //订阅消息 不显示
        this.subscribeMessagesVisible = false
        //订阅--响应数据
        this.subscribeResponseDataVisible = false
        //相应数据 不显示
        this.responseDataVisible = false
        //推送--数据类型
        this.pushDataTypeVisible = false
      } else if (type === 'MQTT_CLIENT') {
        //订阅消息
        this.subscribeMessagesVisible = true
        //推送消息
        this.pushMessageVisible = true
        //订阅消息--订阅Topic
        this.subscribeTopicVisible = true
        //订阅消息--数据类型
        this.subscribeDataTypeVisible = true
        // topic
        this.topicVisible = true
        //推送数据
        this.pushDataVisible = true
        //推送--数据类型
        this.pushDataTypeVisible = true

        //相应数据 不显示
        this.responseDataVisible = false
        //数据类型 不显示
        this.dataTypeVisible = false
        ////推送--请求数据 不显示
        this.pushRequestDataVisible = false
        //订阅--响应数据
        this.subscribeResponseDataVisible = false
      } else {
        //响应数据 不显示
        this.responseDataVisible = false
        //数据类型 不显示
        this.dataTypeVisible = false
        //订阅消息--订阅Topic 不显示
        this.subscribeTopicVisible = false
        //订阅消息--数据类型 不显示
        this.subscribeDataTypeVisible = false
        //推送--Topic
        this.topicVisible = false
        //推送--数据
        this.pushDataVisible = false

        //推送--请求数据 不显示
        this.pushRequestDataVisible = false
        //推送消息 不显示
        this.pushMessageVisible = false
        //订阅消息 不显示
        this.subscribeMessagesVisible = false
        //订阅--响应数据
        this.subscribeResponseDataVisible = false

        //推送--数据类型
        this.pushDataTypeVisible = false

      }

    }

  }
}
</script>

<style scoped>
.debug-result {
  height: 250px;
  overflow: auto;
}
</style>
